package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;

import com.next.easynavigation.view.EasyNavigationBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.databinding.ActivityMainBinding;
import org.video.mine.entity.LoadedEntity;
import org.video.mine.entity.LoadingEntity;
import org.video.mine.entity.ProgressLoadEntity;
import org.video.mine.event.LoadErrorEvent;
import org.video.mine.event.LoadFailedEvent;
import org.video.mine.event.NotifyLoadingPos;
import org.video.mine.fragment.HomeFragment;
import org.video.mine.fragment.MineFragment;
import org.video.mine.model.MainViewModel;
import org.video.mine.mycode.DownTask;
import org.video.mine.mycode.DownThread;
import org.video.mine.network.JsoupGet;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

import static org.video.mine.mycode.DownTask.downThreadList;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    private String[] navTitle = {"首页","其它"};
    private int[] navImageCancel = {R.drawable.shouye,R.drawable.mine};
    private int[] navImageSelect = {R.drawable.shouye1,R.drawable.mine1};
    private List<Fragment> fragments = new ArrayList<>();
    private long pressTime = 0;
    private MainActivity context;
    private MyPreference preference;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(context, (CharSequence) msg.obj,Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        setContentView(binding.getRoot());
        requestIgnoreBatteryOptiomzations();
        context = this;
        EventBus.getDefault().register(this);
        GlobalStr.context = context;
        GlobalStr.handler = handler;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermission();
        }
        initView();
        initData();
    }

    private void initData() {
        preference = MyPreference.getInstance();
        preference.setPreference(context);
        List<LoadingEntity> loadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
        if (loadingEntities==null){
            loadingEntities = new ArrayList<>();
        }
        downThreadList = new ArrayList<>();
        for (final LoadingEntity loadingEntity:loadingEntities){
            if (loadingEntity.getAllCount()==0){
                final List<LoadingEntity> finalLoadingEntities = loadingEntities;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        List<List> lists = JsoupGet.getTs(loadingEntity.getUrl());
                        if (lists.size()>1) {
                            finalLoadingEntities.get(finalLoadingEntities.indexOf(loadingEntity)).setAllCount(lists.get(1).size());
                        }
                        preference.setObject(MyPreference.loading,finalLoadingEntities);
                    }
                }).start();
            }
            DownThread thread = new DownThread(loadingEntity.getUrl(), loadingEntity.getName(), loadingEntity.getSet(), context, loadingEntity.getImgUrl());
            downThreadList.add(thread);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.INTERNET,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new io.reactivex.Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initView() {
        fragments.add(HomeFragment.newInstance());
        fragments.add(MineFragment.newInstance());
        binding.navigationBar.titleItems(navTitle)
                .normalIconItems(navImageCancel)
                .selectIconItems(navImageSelect)
                .fragmentList(fragments)
                .fragmentManager(getSupportFragmentManager())
                .selectTextColor(Color.parseColor("#1296DB"))
                .normalTextColor(Color.parseColor("#8a8a8a"))
                .setOnTabClickListener(new EasyNavigationBar.OnTabClickListener() {
                    @Override
                    public boolean onTabSelectEvent(View view, int position) {

                        return false;
                    }

                    @Override
                    public boolean onTabReSelectEvent(View view, int position) {
                        return false;
                    }
                })
                .build();
    }

    private void requestIgnoreBatteryOptiomzations() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        try {
            String packageName = getApplicationContext().getPackageName();
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            if (pm.isIgnoringBatteryOptimizations(packageName)) return;
            Intent intent = new Intent();
            //第二种方法，弹出框选择是否加入电池白名单
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:"+packageName));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        boolean isLoading = false;
        for (DownThread thread:downThreadList){
            if (thread.isLoading){
                isLoading = true;
                break;
            }
        }
        if (isLoading) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("正在下载中，退出将停止下载哦~");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }else {
            if (System.currentTimeMillis()-pressTime<1000){
                super.onBackPressed();
            }else {
                pressTime = System.currentTimeMillis();
                Toast.makeText(MainActivity.this,"再按一次退出爱视频",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void loadFailed(LoadFailedEvent event){
        if (event!=null){
            Message message = Message.obtain();
            message.what = 0;
            message.obj = event.msg;
            handler.sendMessage(message);
//            Toast.makeText(getContext(), event.msg,Toast.LENGTH_SHORT).show();
        }
    }


    @Subscribe
    public void downErrorEvent(LoadErrorEvent event){
        if (event!=null){
            DownTask.stopThread(event.name,event.set);
        }
    }


}
